﻿using JsonArchive;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace HousekeepingSystem
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            LoadEmployeeList();
        }

        private Dictionary<string, object> EmployeeList = new Dictionary<string, object>();

        private void LoadEmployeeList()
        {
            String JSON = File.ReadAllText(Application.StartupPath + @"\info\EmployeeList.json");
            EmployeeList = J2D.JsonToDictionary(JSON);
            SetEmployeeList();
        }
        private void SetEmployeeList()
        {
            listView1.BeginUpdate();
            listView1.Items.Clear();
            foreach (var item in EmployeeList)
            {
                if (item.Key == "0") continue;
                ListViewItem EmployeeRow = new ListViewItem();
                EmployeeRow.Text = item.Key;
                foreach (var data in (ArrayList)item.Value)
                {
                    EmployeeRow.SubItems.Add(data.ToString());
                }
                listView1.Items.Add(EmployeeRow);
            }
            listView1.EndUpdate();
        }
        
        //禁止调节表格宽度
        private void listView1_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
        {
            e.Cancel = true;
            e.NewWidth = listView1.Columns[e.ColumnIndex].Width;
        }

        //添加员工
        private void button1_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            if (new Form2_1().ShowDialog() == DialogResult.OK)
            {
                LoadEmployeeList();
            };
        }
        
        //删除员工
        private void button2_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            if (listView1.CheckedItems.Count < 1)
            {
                MessageBox.Show("没有被选中的项！", "错误");
                return;
            }
            if (MessageBox.Show("确定要删除选定项?", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                foreach (ListViewItem item in listView1.CheckedItems)
                {
                    EmployeeList.Remove(item.Text);
                }
                SetEmployeeList();
                saveEmployeeList();
            }
        }

        //做工记录
        private void button3_Click(object sender, EventArgs e)
        {
            panel1.Focus();

        }

        //导出名单
        private void button4_Click(object sender, EventArgs e)
        {
            panel1.Focus();
            button4.Enabled = false;

            // 创建Excel文档
            Excel.Application ExcelApp = new Excel.Application();
            Excel.Workbook ExcelDoc = ExcelApp.Workbooks.Add(Type.Missing);
            Excel.Worksheet xlSheet = ExcelDoc.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            ExcelApp.DisplayAlerts = false;
            // 单元格下标是从[1，1]开始的
            Int32 Row = 1;
            Int32 Column = 1;
            //获取表头
            xlSheet.Cells[Row, Column] = "序号";
            for (int i = 1; i < listView1.Columns.Count; i++)
            {
                xlSheet.Cells[Row, Column + i] = listView1.Columns[i].Text;
            }
            //获取内容
            foreach (ListViewItem item in listView1.Items)
            {
                ++Row;
                xlSheet.Cells[Row, Column] = Row - 1;
                for (int i = 1; i < item.SubItems.Count; i++)
                {
                    xlSheet.Cells[Row, Column + i] = item.SubItems[i].Text;
                }
            }
            //自动列宽
            xlSheet.Cells.EntireColumn.AutoFit();

            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Title = "保存Excel文件";
            saveFile.Filter = "Excel文件|*.xlsx";
            Boolean FileIsUsed = true;
            while (FileIsUsed)
            {
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (File.Exists(saveFile.FileName))
                        {
                            File.Move(saveFile.FileName, saveFile.FileName);
                        }
                        FileIsUsed = false;
                    }
                    catch (Exception)
                    {
                        FileIsUsed = true;
                    }
                }
                else
                {
                    break;
                }
                if (FileIsUsed)
                {
                    if (MessageBox.Show("指定文件已被占用，请关闭后重试！", "Error", MessageBoxButtons.RetryCancel) == DialogResult.Cancel)
                    {
                        break;
                    }
                }
                else
                {
                    // 文件保存
                    xlSheet.SaveAs(saveFile.FileName);
                    ExcelDoc.Close(Type.Missing, saveFile.FileName, Type.Missing);
                    ExcelApp.Quit();
                }
            }

            button4.Enabled = true;
        }

        private void saveEmployeeList()
        {
            int listIndex = 0;
            EmployeeList.Clear();
            ArrayList EmployeeRowValue = new ArrayList();
            for (int i = 1; i < listView1.Columns.Count; i++)
            {
                EmployeeRowValue.Add(listView1.Columns[i].Text);
            }
            EmployeeList.Add(listIndex.ToString(), EmployeeRowValue.ToArray());
            foreach (ListViewItem Item in listView1.Items)
            {
                EmployeeRowValue.Clear();
                for (int i = 1; i < Item.SubItems.Count; i++)
                {
                    EmployeeRowValue.Add(Item.SubItems[i].Text);
                }
                EmployeeList.Add((++listIndex).ToString(), EmployeeRowValue.ToArray());
            }
            String JSON = D2J.DictionaryToJson(EmployeeList);
            File.WriteAllText(Application.StartupPath + @"\info\EmployeeList.json", JSON);
        }

        private void Form2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Escape)
            {
                this.Close();
                e.Handled = true;
            }
        }
    }
}
